<html lang="zh-CN"><head><meta charset="UTF-8"><style>.nodata  main {width:1000px;margin: auto;}</style></head><body class="nodata " style=""><div class="main_father clearfix d-flex justify-content-center " style="height:100%;"> <div class="container clearfix " id="mainBox"><main><div class="blog-content-box">
<div class="article-header-box">
<div class="article-header">
<div class="article-title-box">
<h1 class="title-article" id="articleContentId">(A卷,100分)- 单向链表中间节点（Java & JS & Python）</h1>
</div>
</div>
</div>
<div id="blogHuaweiyunAdvert"></div>

        <div id="article_content" class="article_content clearfix">
        <link rel="stylesheet" href="https://csdnimg.cn/release/blogv2/dist/mdeditor/css/editerView/kdoc_html_views-1a98987dfd.css">
        <link rel="stylesheet" href="https://csdnimg.cn/release/blogv2/dist/mdeditor/css/editerView/ck_htmledit_views-044f2cf1dc.css">
                <div id="content_views" class="htmledit_views">
                    <h4 id="main-toc">题目描述</h4> 
<p>求单向链表中间的节点值&#xff0c;如果奇数个节点取中间&#xff0c;偶数个取偏右边的那个值。</p> 
<p></p> 
<h4 id="%E8%BE%93%E5%85%A5%E6%8F%8F%E8%BF%B0">输入描述</h4> 
<p>第一行 链表头节点地址 后续输入的节点数n</p> 
<p>后续输入每行表示一个节点&#xff0c;格式 节点地址 节点值 下一个节点地址(-1表示空指针)</p> 
<p>输入保证链表不会出现环&#xff0c;并且可能存在一些节点不属于链表。</p> 
<p></p> 
<h4 id="%E8%BE%93%E5%87%BA%E6%8F%8F%E8%BF%B0">输出描述</h4> 
<p>单向链表中间的节点值</p> 
<p></p> 
<h4 id="%E7%94%A8%E4%BE%8B">用例</h4> 
<table border="1" cellpadding="1" cellspacing="1" style="width:500px;"><tbody><tr><td style="width:86px;">输入</td><td style="width:412px;">00010 4<br /> 00000 3 -1<br /> 00010 5 12309<br /> 11451 6 00000<br /> 12309 7 11451</td></tr><tr><td style="width:86px;">输出</td><td style="width:412px;">6</td></tr><tr><td style="width:86px;">说明</td><td style="width:412px;">无</td></tr></tbody></table> 
<table border="1" cellpadding="1" cellspacing="1" style="width:500px;"><tbody><tr><td style="width:85px;">输入</td><td style="width:413px;">10000 3<br /> 76892 7 12309<br /> 12309 5 -1<br /> 10000 1 76892</td></tr><tr><td style="width:85px;">输出</td><td style="width:413px;">7</td></tr><tr><td style="width:85px;">说明</td><td style="width:413px;">无</td></tr></tbody></table> 
<h4 id="%E9%A2%98%E7%9B%AE%E8%A7%A3%E6%9E%90">题目解析</h4> 
<p>用例1示意图如下</p> 
<p><img alt="" height="157" src="https://img-blog.csdnimg.cn/cde07b53555e450db908855d88bb2ab0.png" width="751" /></p> 
<p>JS本题可以利用数组模拟链表 </p> 
<p></p> 
<h3>基于链表数据结构解题</h3> 
<h4 id="%E7%AE%97%E6%B3%95%E6%BA%90%E7%A0%81">JavaScript算法源码</h4> 
<pre><code class="language-javascript">/* JavaScript Node ACM模式 控制台输入获取 */
const readline &#61; require(&#34;readline&#34;);

const rl &#61; readline.createInterface({
  input: process.stdin,
  output: process.stdout,
});

const lines &#61; [];
let head;
let n;
rl.on(&#34;line&#34;, (line) &#61;&gt; {
  lines.push(line);

  if (lines.length &#61;&#61;&#61; 1) {
    [head, n] &#61; lines[0].split(&#34; &#34;);
  }

  if (n &amp;&amp; lines.length &#61;&#61;&#61; n - 0 &#43; 1) {
    lines.shift();

    const nodes &#61; {};

    lines.forEach((line) &#61;&gt; {
      const [addr, val, nextAddr] &#61; line.split(&#34; &#34;);
      nodes[addr] &#61; [val, nextAddr];
    });

    console.log(getResult(head, nodes));

    lines.length &#61; 0;
  }
});

function getResult(head, nodes) {
  const linkedlist &#61; [];

  let node &#61; nodes[head];
  while (node) {
    const [val, next] &#61; node;

    linkedlist.push(val);
    node &#61; nodes[next];
  }

  const len &#61; linkedlist.length;

  const mid &#61; len % 2 &#61;&#61;&#61; 0 ? len / 2 : Math.floor(len / 2);

  return linkedlist[mid];
}
</code></pre> 
<p></p> 
<h4>Java算法源码</h4> 
<p>需要注意的是Java中LinkedList类的get(index)方法的时间复杂度不是O(1)&#xff0c;而是O(n)&#xff0c;这题建议使用ArrayList代替</p> 
<pre><code class="language-java">import java.util.ArrayList;
import java.util.HashMap;
import java.util.Scanner;

public class Main {
  public static void main(String[] args) {
    Scanner sc &#61; new Scanner(System.in);

    String head &#61; sc.next();
    int n &#61; sc.nextInt();

    HashMap&lt;String, String[]&gt; nodes &#61; new HashMap&lt;&gt;();
    for (int i &#61; 0; i &lt; n; i&#43;&#43;) {
      String addr &#61; sc.next();
      String val &#61; sc.next();
      String nextAddr &#61; sc.next();
      nodes.put(addr, new String[] {val, nextAddr});
    }

    System.out.println(getResult(head, nodes));
  }

  public static String getResult(String head, HashMap&lt;String, String[]&gt; nodes) {
    //    LinkedList&lt;String&gt; link &#61; new LinkedList&lt;&gt;();
    ArrayList&lt;String&gt; link &#61; new ArrayList&lt;&gt;();

    String[] node &#61; nodes.get(head);
    while (node !&#61; null) {
      String val &#61; node[0];
      String next &#61; node[1];

      link.add(val);
      node &#61; nodes.get(next);
    }

    int len &#61; link.size();
    int mid &#61; len / 2;
    return link.get(mid);
  }
}
</code></pre> 
<p></p> 
<h4>Python算法源码</h4> 
<pre><code class="language-python"># 输入获取
head, n &#61; input().split()

nodes &#61; {}
for i in range(int(n)):
    addr, val, nextAddr &#61; input().split()
    nodes[addr] &#61; [val, nextAddr]


# 算法入口
def getResult(head, nodes):
    linkedlist &#61; []
    node &#61; nodes.get(head)

    while node is not None:
        val, next &#61; node
        linkedlist.append(val)
        node &#61; nodes.get(next)

    length &#61; len(linkedlist)
    mid &#61; int(length / 2)

    return linkedlist[mid]


# 算法调用
print(getResult(head, nodes))
</code></pre> 
<p></p> 
<h3>快慢指针解题</h3> 
<p>链表数据结构本质上来说没有索引概念&#xff0c;因为其在内存上不是一段连续的内存&#xff0c;因此索引对于链表结构而言没有意义。</p> 
<p>但是从使用上来说&#xff0c;我又经常需要去获取链表结构的第几个元素&#xff0c;因此大部分语言都为链表结构提高了“假索引”&#xff0c;比如Java的LinkedList类&#xff0c;虽然提高了get(index)方法&#xff0c;但是其底层是通过遍历链表&#xff08;通过next属性找到下一个节点&#xff09;来找到对应“假索引”的元素的&#xff0c;即LinkedList每次都需要O(n)的时间复杂度才能找到index位置上的元素。</p> 
<p></p> 
<p>另外&#xff0c;链表还有一个常考问题&#xff0c;那就是链表长度未知的情况下&#xff0c;我们如何找到链表的中间节点&#xff1f;</p> 
<p>此时&#xff0c;就要用到快慢指针。</p> 
<p>所谓快慢指针&#xff0c;即通过两个指针遍历链表&#xff0c;慢指针每次步进1个节点&#xff0c;快指针每次步进2个节点&#xff0c;这样快指针必然先到达链表尾部&#xff0c;而当快指针到达链表尾部时&#xff0c;慢指针其实刚好就是在链表中间节点的位置&#xff08;奇数个节点取中间&#xff0c;偶数个取偏右边的那个值&#xff09;。</p> 
<p></p> 
<p>本题虽然给出了节点数&#xff0c;但是这些节点不一定属于同一个链表结构&#xff0c;因此本题的链表长度也是未知的&#xff0c;而本题要求的链表中间节点要求刚好和快慢指针找的中间节点吻合&#xff0c;因此本题最佳策略是使用快慢指针。</p> 
<p></p> 
<h4>Java算法源码</h4> 
<pre><code class="language-java">import java.util.HashMap;
import java.util.Scanner;

public class Main {
  public static void main(String[] args) {
    Scanner sc &#61; new Scanner(System.in);

    String head &#61; sc.next();
    int n &#61; sc.nextInt();

    HashMap&lt;String, String[]&gt; nodes &#61; new HashMap&lt;&gt;();
    for (int i &#61; 0; i &lt; n; i&#43;&#43;) {
      String addr &#61; sc.next();
      String val &#61; sc.next();
      String nextAddr &#61; sc.next();
      nodes.put(addr, new String[] {val, nextAddr});
    }

    System.out.println(getResult(head, nodes));
  }

  public static String getResult(String head, HashMap&lt;String, String[]&gt; nodes) {
    String[] slow &#61; nodes.get(head);
    String[] fast &#61; nodes.get(slow[1]);

    while (fast !&#61; null) {
      slow &#61; nodes.get(slow[1]);

      fast &#61; nodes.get(fast[1]);
      if (fast !&#61; null) {
        fast &#61; nodes.get(fast[1]);
      } else {
        break;
      }
    }

    return slow[0];
  }
}
</code></pre> 
<h4>JavaScript算法源码</h4> 
<pre><code class="language-javascript">/* JavaScript Node ACM模式 控制台输入获取 */
const readline &#61; require(&#34;readline&#34;);

const rl &#61; readline.createInterface({
  input: process.stdin,
  output: process.stdout,
});

const lines &#61; [];
let head;
let n;
rl.on(&#34;line&#34;, (line) &#61;&gt; {
  lines.push(line);

  if (lines.length &#61;&#61;&#61; 1) {
    [head, n] &#61; lines[0].split(&#34; &#34;);
  }

  if (n &amp;&amp; lines.length &#61;&#61;&#61; n - 0 &#43; 1) {
    lines.shift();

    const nodes &#61; {};

    lines.forEach((line) &#61;&gt; {
      const [addr, val, nextAddr] &#61; line.split(&#34; &#34;);
      nodes[addr] &#61; [val, nextAddr];
    });

    console.log(getResult(head, nodes));

    lines.length &#61; 0;
  }
});

function getResult(head, nodes) {
  let slow &#61; nodes[head];
  let fast &#61; nodes[slow[1]];

  while (fast) {
    slow &#61; nodes[slow[1]];

    fast &#61; nodes[fast[1]];
    if (fast) {
      fast &#61; nodes[fast[1]];
    } else {
      break;
    }
  }

  return slow[0];
}
</code></pre> 
<h4>Python算法源码</h4> 
<pre><code class="language-python"># 输入获取
head, n &#61; input().split()

nodes &#61; {}
for i in range(int(n)):
    addr, val, nextAddr &#61; input().split()
    nodes[addr] &#61; [val, nextAddr]


# 算法入口
def getResult(head, nodes):
    slow &#61; nodes.get(head)
    fast &#61; nodes.get(slow[1])

    while fast is not None:
        slow &#61; nodes.get(slow[1])

        fast &#61; nodes.get(fast[1])
        if fast is None:
            break
        else:
            fast &#61; nodes.get(fast[1])

    return slow[0]


# 算法调用
print(getResult(head, nodes))
</code></pre> 
<p></p>
                </div>
        </div>
        <div id="treeSkill"></div>
        <div id="blogExtensionBox" style="width:400px;margin:auto;margin-top:12px" class="blog-extension-box"></div>
    <script>
  $(function() {
    setTimeout(function () {
      var mathcodeList = document.querySelectorAll('.htmledit_views img.mathcode');
      if (mathcodeList.length > 0) {
        for (let i = 0; i < mathcodeList.length; i++) {
          if (mathcodeList[i].naturalWidth === 0 || mathcodeList[i].naturalHeight === 0) {
            var alt = mathcodeList[i].alt;
            alt = '\\(' + alt + '\\)';
            var curSpan = $('<span class="img-codecogs"></span>');
            curSpan.text(alt);
            $(mathcodeList[i]).before(curSpan);
            $(mathcodeList[i]).remove();
          }
        }
        MathJax.Hub.Queue(["Typeset",MathJax.Hub]);
      }
    }, 1000)
  });
</script>
</div></html>